package com.fuatnow.game.handler;

import com.fuatnow.game.database.DBHelper;
import com.fuatnow.game.entity.User;
import com.fuatnow.game.entity.JsonMessage;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

import static com.fuatnow.game.constant.ProtocolConstant.USER_REG;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by fuatnow on 17/1/19.
 */
public class RegisterHandler extends MsgHander
{
    private FullHttpRequest _req;
    private User _user;
    public RegisterHandler(ChannelHandlerContext ctx, FullHttpRequest req, User user)
    {
        super(ctx, "");
        _req = req;
        _user = user;
    }

    @Override
    public void processMsg() throws Exception
    {
        JsonMessage jMsg = new JsonMessage(USER_REG);
        try
        {
        //先给适当的金币
            String sqlStr="insert into UserInfo(usrName,pwd,lastlogin) values('"+_user.getUsrName()+"','"
                +_user.getPassword()+"','"+_user.getLastLogin()+"');";
            boolean isOk = DBHelper.getInstance().setSql(sqlStr);
            if(isOk)
            {
                String selSql = "select max(usrID) from UserInfo;";
                ResultSet res = DBHelper.getInstance().getResultSet(selSql);
                if (res != null && res.next()) {
                    int usrID = res.getInt(1);
                    _user.setUsrID(usrID);
                    jMsg.put("usrID", usrID);
                    jMsg.put(JsonMessage.ERROR_CODE_KEY,0);
                    String jsonStr = jMsg.toString();
                    ByteBuf content = Unpooled.wrappedBuffer(jsonStr.getBytes());
                    FullHttpResponse fResp = new DefaultFullHttpResponse(HTTP_1_1, OK, content);
                    fResp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
                    HttpUtil.setContentLength(fResp, content.readableBytes());
                    sendHttpResponse(_ctx, _req, fResp);
                    return;
                }
            }
        }
        catch (Exception e)
        {
            _user.setUsrID(-1);
            System.err.print(e.getStackTrace());
        }

        jMsg.put(JsonMessage.ERROR_CODE_KEY,1);
        jMsg.put(JsonMessage.ERROR_MSG_KEY,"unknown");
        String jsonStr = jMsg.toString();

        ByteBuf content = Unpooled.wrappedBuffer(jsonStr.getBytes());
        FullHttpResponse fResp = new DefaultFullHttpResponse(HTTP_1_1, OK,content );
        fResp.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
        HttpUtil.setContentLength(fResp, content.readableBytes());
        sendHttpResponse(_ctx, _req, fResp);
    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // Generate an error page if response getStatus code is not OK (200).
        if (res.status().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }

        // Send the response and close the connection if necessary.
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }
    }

    public static User getRegUser(Map<String, List<String>> params)
    {
        if(params.containsKey("usr") && params.containsKey("pwd"))
        {
            try{
                String usrName = params.get("usr").get(0);
                String pwdName = params.get("pwd").get(0);
                User reg = new User();
                reg.setUsrName(usrName);
                reg.setPassword(pwdName);
                return  reg;
            }
            catch (Exception e)
            {
                return  null;
            }
        }
        return  null;
    }
}
